<template>
  <div>
    <Form :label-width="118" :model="formData" ref="formItem" :rules="rules">
      <Row :gutter="48">
        <i-col span="16">
          <FormItem label="视频标题" prop="title">
            <Input placeholder="请输入视频标题" v-model="formData.title" />
          </FormItem>
          <FormItem label="视频类型" prop="video_type_id">
            <Select placeholder="视频类型" v-model="formData.video_type_id" clearable>
              <Option
                v-for="(item, index) in typelist"
                :value="+item.value"
                :key="index"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>

          <FormItem label="视频ID" prop="video_id">
            <Input
              placeholder="请输入视频ID,视频ID从视频后台获取"
              v-model="formData.video_id"
            />
          </FormItem>
        </i-col>
        <i-col span="8">
          <FormItem label="封面图" prop="cover_img" :label-width="80">
            <div v-if="formData.cover_img">
              <img :src="formData.cover_img" width="100" height="100" />
            </div>
            <div class="imageUpdate">
              <Upload
                ref="upload"
                name="file"
                :show-upload-list="false"
                :on-success="handleSuccess"
                :format="['jpg', 'jpeg', 'png']"
                :action="requestAction"
                :before-upload="handleBefore"
              >
                <div>
                  <Button
                    type="primary"
                    class="ivu-mr-8"
                    size="small"
                    :loading="loading"
                  >
                    {{ loading ? "上传中..." : "上传" }}
                  </Button>
                </div>
              </Upload>
              <Button type="success" size="small" @click="showImgModel = true"
                >选择</Button
              >
            </div>
          </FormItem>
          <FormItem
            label="排序"
            prop="sort"
            class="ivu-inline-block"
            :label-width="80"
          >
            <InputNumber :precision="0" :min="0" v-model="formData.sort" />
          </FormItem>
          <FormItem
            label="收藏"
            prop="sub_config_num"
            class="ivu-inline-block"
            :label-width="80"
          >
            <InputNumber
              :precision="0"
              :min="0"
              v-model="formData.sub_config_num"
            />
          </FormItem>
          <FormItem label="标签" prop="model1" :label-width="80">
            <Select
              v-model="formData.model1"
              filterable
              multiple
              allow-create
              @on-change="selectTag"
              @on-create="handleCreate"
            >
              <Option
                v-for="item in tagList"
                :value="+item.value"
                :key="item.value"
                :disabled="+item.disabled === 1 ? false : true"
                >{{ item.label }}</Option
              >
            </Select>
          </FormItem>
          <FormItem label="状态" prop="status" :label-width="80">
            <RadioGroup v-model="formData.status">
              <Radio :label="1">正常</Radio>
              <Radio :label="0">停用</Radio>
            </RadioGroup>
          </FormItem>
          <FormItem label="首页推荐" prop="recommend_type" :label-width="80">
            <Switch v-model="formData.recommend_type" />
          </FormItem>
        </i-col>
      </Row>
    </Form>
    <glo-check v-model="showImgModel" @getImgArr="getImgArr" />
  </div>
</template>
<script>
import { videoCreate, videoUpdate, backendInfo } from "@/api/video"
import { updatefileTemp } from '@/api/set.js'
import Setting from "@/setting"
import util from "@/libs/util"
export default {
  name: "modalName",
  props: ["editorType"],
  data () {
    return {
      loading: false,
      showImgModel: false,
      baseUrl: Setting.request.apiBaseURL,
      requestAction: "",
      tagList: [],
      typelist: {},
      model1:[],
      formData: {
        title: "",
        video_type_id: "",
        cover_img: "",
        video_id: "",
        sort: 1,
        model1:[],
        tag:[],
        sub_config_num: '',
        status: 1,
        recommend_type: false,
      },
      rules: {
        title: [
          { required: true, message: "请输入视频标题", trigger: "bulr" },
          { trigger: "bulr", validator: this.watermarkContentVaild },
        ],
        video_type_id: [
          {
            required: true,
            message: "请选择视频类型",
            trigger: "change,bulr",
            type: "number",
          },
        ],
        video_id: [
          { required: true, message: "请输入视频ID", trigger: "change" },
        ],
        cover_img: [
          { required: true, message: "请选择视频封面", trigger: "bulr" }
        ]
      },
      videoId: "",
      initTagList: [],
      tagList: [],
    }
  },
  methods: {
    resetForm () {
      this.$refs.formItem.resetFields()
    },
    watermarkContentVaild (rule, value, callback) {
      let length = value.replace(/[^\x00-\xff]/g, "01").length
      if (length > 36) {
        callback(new Error("请输入1~18个汉字"))
      } else {
        callback()
      }
    },
    infoData (id) {
      backendInfo({ id: id }).then((res) => {
        this.typelist = res.condition.type
        this.initTagList = [...res.condition.tag]
        this.tagList = res.condition.tag
        if (id > 0) {
          this.formData = {
            title: res.title,
            video_type_id: res.video_type_id,
            cover_img: res.cover_img,
            video_id: res.video_id,
            sort: res.sort,
             model1: res.tag_ids,
            tag: [],
            sub_config_num: res.sub_config_num,
            status: res.status,
            recommend_type: res.recommend_type == 1 ? true : false,
          }
          this.videoId = res.id
        } else {
          this.formData = {
            title: "",
            video_type_id: "",
            cover_img: "",
            video_id: "",
            sort: 1,
            model1: [],
            tag: [],
            sub_config_num: '',
            status: 1,
            recommend_type: false,
          }
        }
      })
    },
    handleCreate (e) {
      if(e.trim().length<1){
        this.$Message['warning']('标签不能为空')
        return
      }else if (e.length > 6) {
        this.$Message['warning']('标签长度不能超过6')
        return
      } else {
        let add=true
        this.tagList.forEach(item=>{
          if(item.label==e){
            add=false
            return;
          }
        })
        if(add){
          var id=new Date().getTime()      
          this.tagList.push({
            value: id,
            label: e,
            disabled: '1',
          })  
        }
         
      }
    },
    selectTag (e) {
      this.tagList.forEach(item=>{
        if(e[e.length - 1]==item.label){            
         if(e.includes(+item.value)){
           e.pop()
         }else{
           e[e.length - 1]=+item.value
         }
        }
      })
      if (e.length && (e[e.length - 1].length > 6||e[e.length - 1].toString().trim().length<1)) {
        e.pop()
        return
      }
      if (e.length > 3) {
        this.$Message.warning("标签不能超过三个~")
        e.splice(3, 1)
        return
      }
    },
    handleBefore () {
      this.loading = true
    },
    handleSuccess (response, file, fileList) {
      this.formData.cover_img = `${response.data.host}${response.data.image_url[0]}`
      this.loading = false
      const id = response.data.image_id[0]
      updatefileTemp({ id })
    },
    getImgArr (arr) {
      this.formData.cover_img = arr[0]
    },
    saveData () {
      this.$refs["formItem"].validate((valid) => {
        if (valid) {
          this.formData.tag = []
          this.formData.model1.forEach((item) => {
            let flag = true,add=true
            this.initTagList.forEach(ele => {
              if (+ele.value == +item) {
                this.formData.tag.push({ id: item, name: ele.label })
                flag = false
                add=false
              }
            })
            if (flag) {
              this.tagList.forEach(ele => {
                if (+ele.value == +item) {
                  this.formData.tag.push({ id: 0, name: ele.label })
                  flag = true
                   add=false
                }
              })
              if(add){
                this.formData.tag.push({ id: 0, name: item })
              }
              
            }
          })
          let params={...this.formData}
           params.recommend_type = params.recommend_type? "1" : "2"
          if (this.editorType) {
            videoCreate(params).then((res) => {
              this.$emit("refresh", false)
            })
          } else {
            videoUpdate(
              Object.assign({}, params, { id: this.videoId })
            ).then((res) => {
              this.$emit("refresh", false)
            })
          }
        }
      })
    },
  },
  mounted () {
    this.requestAction =
      this.baseUrl +
      `/v1/upload/images?auth_access_token=${util.cookies.get(
        "token"
      )}&auth_project_id=${localStorage.getItem('currentProject')}`
  },
};
</script>
<style lang='less' scoped>
.ivu-modal {
  top: 50px;
}
.imageUpdate {
  display: flex;
}
.imageUpdate button {
  vertical-align: top;
}
.ck.ck-editor__main > .ck-editor__editable {
  height: 400px;
}
</style>